<template>
  <div class="loop-node-config">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="节点名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入节点名称" />
      </el-form-item>
      
      <el-form-item label="循环类型" prop="loopType">
        <el-select v-model="form.loopType" style="width: 100%" @change="onLoopTypeChange">
          <el-option label="计数循环" value="count" />
          <el-option label="条件循环" value="while" />
          <el-option label="遍历循环" value="foreach" />
        </el-select>
      </el-form-item>

      <!-- 计数循环配置 -->
      <div v-if="form.loopType === 'count'">
        <el-form-item label="循环次数" prop="count">
          <el-input-number 
            v-model="form.count" 
            :min="1" 
            :max="1000" 
            style="width: 100%" 
            placeholder="循环执行的次数"
          />
        </el-form-item>
        <el-form-item label="循环变量">
          <el-input 
            v-model="form.indexVariable" 
            placeholder="例如: i, index (可选，从0开始)"
          >
            <template #suffix>
              <el-tooltip content="循环索引变量名&#10;可在循环体中使用 {indexVariable}" placement="top">
                <el-icon style="cursor: help"><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <!-- 条件循环配置 -->
      <div v-else-if="form.loopType === 'while'">
        <el-form-item label="循环条件" prop="condition">
          <el-input 
            v-model="form.condition" 
            type="textarea" 
            :rows="3"
            placeholder="JavaScript表达式，例如: variables.count < 10"
          >
            <template #suffix>
              <el-tooltip content="JavaScript条件表达式&#10;可用变量: variables, response, iteration" placement="top">
                <el-icon style="cursor: help"><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="最大循环次数" prop="maxIterations">
          <el-input-number 
            v-model="form.maxIterations" 
            :min="1" 
            :max="1000" 
            style="width: 100%" 
            placeholder="防止无限循环"
          />
        </el-form-item>
      </div>

      <!-- 遍历循环配置 -->
      <div v-else-if="form.loopType === 'foreach'">
        <el-form-item label="数组来源" prop="arraySource">
          <el-select v-model="form.arraySource" style="width: 100%" @change="onArraySourceChange">
            <el-option label="变量" value="variable" />
            <el-option label="JSONPath" value="jsonpath" />
            <el-option label="静态数组" value="static" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="form.arraySource === 'variable'" label="变量名" prop="arrayVariable">
          <el-input 
            v-model="form.arrayVariable" 
            placeholder="例如: userList, items"
          />
        </el-form-item>
        
        <el-form-item v-else-if="form.arraySource === 'jsonpath'" label="JSONPath" prop="arrayPath">
          <el-input 
            v-model="form.arrayPath" 
            placeholder="例如: $.data.users, $.items"
          />
        </el-form-item>
        
        <el-form-item v-else-if="form.arraySource === 'static'" label="静态数组" prop="staticArray">
          <el-input 
            v-model="form.staticArray" 
            type="textarea" 
            :rows="3"
            placeholder='JSON数组格式，例如: [1,2,3] 或 ["a","b","c"]'
          />
        </el-form-item>
        
        <el-form-item label="循环变量">
          <el-input 
            v-model="form.itemVariable" 
            placeholder="例如: item, user (当前遍历的元素)"
          />
        </el-form-item>
        
        <el-form-item label="索引变量">
          <el-input 
            v-model="form.indexVariable" 
            placeholder="例如: index, i (当前索引，可选)"
          />
        </el-form-item>
      </div>

      <!-- 循环控制 -->
      <el-form-item label="循环控制">
        <div class="loop-control">
          <el-checkbox v-model="form.breakOnFailure">遇到失败时跳出循环</el-checkbox>
          <el-checkbox v-model="form.continueOnFailure">遇到失败时继续下一次循环</el-checkbox>
          <el-checkbox v-model="form.collectResults">收集每次循环的结果</el-checkbox>
        </div>
      </el-form-item>

      <!-- 执行配置 -->
      <el-form-item label="执行配置">
        <div class="execution-config">
          <el-checkbox v-model="form.isEnabled">启用此节点</el-checkbox>
        </div>
      </el-form-item>

      <!-- 循环预览 -->
      <el-form-item label="循环预览">
        <div class="loop-preview">
          <el-tag type="info">{{ getLoopDescription() }}</el-tag>
        </div>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <div class="footer-left">
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          删除节点
        </el-button>
      </div>
      <div class="footer-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { QuestionFilled, Delete } from '@element-plus/icons-vue'

const props = defineProps({
  nodeData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['save', 'cancel', 'delete'])

const formRef = ref()

// 表单数据
const form = reactive({
  name: props.nodeData.data?.label || '循环',
  loopType: props.nodeData.data?.config?.loopType || 'count',
  count: props.nodeData.data?.config?.count || 1,
  condition: props.nodeData.data?.config?.condition || '',
  maxIterations: props.nodeData.data?.config?.maxIterations || 100,
  arraySource: props.nodeData.data?.config?.arraySource || 'variable',
  arrayVariable: props.nodeData.data?.config?.arrayVariable || '',
  arrayPath: props.nodeData.data?.config?.arrayPath || '',
  staticArray: props.nodeData.data?.config?.staticArray || '',
  itemVariable: props.nodeData.data?.config?.itemVariable || 'item',
  indexVariable: props.nodeData.data?.config?.indexVariable || '',
  breakOnFailure: props.nodeData.data?.config?.breakOnFailure || false,
  continueOnFailure: props.nodeData.data?.config?.continueOnFailure || false,
  collectResults: props.nodeData.data?.config?.collectResults || false,
  isEnabled: props.nodeData.data?.config?.isEnabled !== false
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入节点名称', trigger: 'blur' }
  ],
  loopType: [
    { required: true, message: '请选择循环类型', trigger: 'change' }
  ],
  count: [
    { required: true, message: '请输入循环次数', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请输入循环条件', trigger: 'blur' }
  ]
}

// 循环类型变化处理
const onLoopTypeChange = () => {
  // 重置相关字段
  form.count = 1
  form.condition = ''
  form.arraySource = 'variable'
  form.arrayVariable = ''
  form.arrayPath = ''
  form.staticArray = ''
}

// 数组来源变化处理
const onArraySourceChange = () => {
  form.arrayVariable = ''
  form.arrayPath = ''
  form.staticArray = ''
}

// 获取循环描述
const getLoopDescription = () => {
  const { loopType, count, condition, arraySource, arrayVariable, arrayPath } = form
  
  switch (loopType) {
    case 'count':
      return `计数循环 ${count} 次`
    case 'while':
      return `条件循环: ${condition || '未设置条件'}`
    case 'foreach':
      if (arraySource === 'variable') {
        return `遍历变量: ${arrayVariable || '未设置'}`
      } else if (arraySource === 'jsonpath') {
        return `遍历JSONPath: ${arrayPath || '未设置'}`
      } else {
        return '遍历静态数组'
      }
    default:
      return '未知循环类型'
  }
}

// 处理保存
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    const config = {
      loopType: form.loopType,
      count: form.count,
      condition: form.condition,
      maxIterations: form.maxIterations,
      arraySource: form.arraySource,
      arrayVariable: form.arrayVariable,
      arrayPath: form.arrayPath,
      staticArray: form.staticArray,
      itemVariable: form.itemVariable,
      indexVariable: form.indexVariable,
      breakOnFailure: form.breakOnFailure,
      continueOnFailure: form.continueOnFailure,
      collectResults: form.collectResults,
      isEnabled: form.isEnabled
    }
    
    emit('save', {
      name: form.name,
      ...config
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 处理删除
const handleDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这个节点吗？此操作不可撤销。',
    '删除节点',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    emit('delete', props.nodeData)
  }).catch(() => {
    // 用户取消删除
  })
}
</script>

<style scoped>
.loop-node-config {
  max-height: 70vh;
  overflow-y: auto;
  padding: 16px;
  font-size: 13px;
}

/* 表单标签样式优化 */
.loop-node-config :deep(.el-form-item__label) {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
}

/* 输入框字体大小 */
.loop-node-config :deep(.el-input__inner),
.loop-node-config :deep(.el-select .el-input__inner),
.loop-node-config :deep(.el-textarea__inner) {
  font-size: 13px;
}

.loop-control,
.execution-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.loop-preview {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  font-size: 12px;
}

.dialog-footer {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.footer-left {
  display: flex;
}

.footer-right {
  display: flex;
}

.dialog-footer .el-button {
  margin-left: 8px;
  font-size: 13px;
}

.footer-left .el-button {
  margin-left: 0;
  margin-right: 8px;
}
</style>